var isChrome = navigator.userAgent.toUpperCase().indexOf("CHROME") >= 0 ? true : false;
$(document).ready(function () {
	prepare();
	$("#searchProduct").parent().find(".textbox-prompt").prop("placeholder", "如可勾选产品已经满足检测样本，则不需要填写，如可勾选产品不满足检测样本，则可选择对应的产品。");
	$.event.special.valuechange = {
		teardown: function (namespaces) {
			$(this).unbind('.valuechange');
		},
		handler: function (e) {
			$.event.special.valuechange.triggerChanged($(this));
		},
		add: function (obj) {
			$(this).on('keyup.valuechange cut.valuechange paste.valuechange input.valuechange propertychange input',
				obj.selector, $.event.special.valuechange.handler);
		},
		triggerChanged: function (element) {
			var current = element[0].contentEditable === 'true' ? element.html() : element.val()
				, previous = typeof element.data('previous') === 'undefined' ? element[0].defaultValue : element.data('previous');
			if (current !== previous) {
				element.trigger('valuechange', [element.data('previous')]);
				element.data('previous', current);
			}
		}
	};
	//首先屏蔽浏览器tab建功能，不然自己写的功能跟tab建功能重复
	$(document).keydown(function (e) {
		if (e.which == 9) {
			e.preventDefault();
			//如果支持window.event(IE肯定是支持的)
			if (window.event) {
				window.event.keyCode = false;
			}
		}
	});
	var inputArray = []
	var i = 0;
	//找出模版所有的输入框，处理单选框除外）nifty的抽血时间获取不了(fireFox)。。。。
	$(".container select,input:not([type='text'].textbox-text,[id='customerCode'],:hidden,.no-border,.pagination-num,[type='checkbox'],[type='hidden'])").each(function (index, element) {
		inputArray[index] = $(this);
		inputArray[index].focus(function () {
			i = index;
		});
	})
	//设置默认第一个选中焦点
	inputArray[i].focus();
	$("body").on("keydown", function (evt) {
		switch (evt.which) {
			case 37: //左
				if (i == 0) {
					i = inputArray.length - 1
					break;
				} else {
					i--;
				}
				break;
			case 39: //右
				if (i == inputArray.length - 1) {
					i = 0;
					break;
				} else {
					i++;
				}
				break;
			case 9: //tab
				if (i == inputArray.length - 1) {
					i = 0;
					break;
				} else {
					i++;
				}
				break;
			default:
				return;
		}
		inputArray[i].focus();
	})
});
/*$(function(){
	$("#searchProduct").combogrid({
		onSelect:function(index){
			var arr = $("#searchProduct").combogrid('grid').datagrid('getSelections');
			var codes = [];
			for(var i in arr){
				codes.push(arr[i].productCode);
			}
			$("#productCodes").val(codes.join(','));
		},
		onUnselect:function(index){
			var arr = $("#searchProduct").combogrid('grid').datagrid('getSelections');
			var codes = [];
			for(var i in arr){
				codes.push(arr[i].productCode);
			}
			$("#productCodes").val(codes.join(','));
		}
	});
});*/
function prepare() {
	var isChrome=navigator.userAgent.toUpperCase().indexOf("CHROME")>=0?true:false; 
	if (!isChrome) {
		$("input[type='date']").each(function () {
			$(this).addClass("easyui-datebox");
			$(this).css("width", "128px");
			$.parser.parse($(this).parent());
		});
	}
}

function Inital(obj) {
	this.obj = obj;
	thatSampleInfos = obj.sampleInfos;
	this.sel = function (id) {
		this.obj[id] = sel(id);
	};
	this.dat = function (id) {
		this.obj[id] = dat(id);
	};
	this.datYMD = function (id) {
		this.obj[id] = datYMD(id);
	};
	this.ck = function (id) {
		this.obj[id] = ck(id);
	};
	this.ckVl = function (id) {
		this.obj[id] = ckVl(id);
	};
	this.ckArrMulti = function (id) {
		this.obj[id] = ckArrMulti(id);
	}
	this.ckArr = function (id) {
		this.obj[id] = ckArr(id);
	};
	this.ckGrp = function (id, count) {
		this.obj[id] = ckGrp(id, count);
	};
	this.vl = function (id) {
		this.obj[id] = vl(id);
	};
	this.getSampleInfos = function (codes) {
		var productQuerySelectedRows;
		if ($('#productQuery')[0]) {
			productQuerySelectedRows = $('#productQuery').combogrid('grid').datagrid('getSelections');
		}
		this.obj = getSampleInfosUpdate(codes, this.obj);
		if (productQuerySelectedRows) {
			if (this.obj.productCode) {
				this.obj.productCode += ',';
				this.obj.productName += ',';
			}
			var thatobj = this.obj;
			$.each(productQuerySelectedRows, function (idx, row) {
				if (thatobj.productCode) {
					thatobj.productCode += ',';
					thatobj.productName += ',';
				}
				thatobj.productCode += row.productCode;
				thatobj.productName += row.productName;
			});
		}
		var arrSampleInfos = getSampleInfos(codes);
		if (typeof (thatSampleInfos) == 'undefined' || thatSampleInfos == null || thatSampleInfos.length == 0) {
			this.obj.sampleInfos = arrSampleInfos;
			if (productQuerySelectedRows) {
				$.each(productQuerySelectedRows, function (idx, row) {
					this.obj.sampleInfos.push({ productCode: row.productCode, projectCode: row.projectCode });
				});
			}
			var codeArr = [];
			var nameArr = [];
			for (var i = 0; i < arrSampleInfos.length; i++) {
				codeArr.push(arrSampleInfos[i].productCode);
				nameArr.push(arrSampleInfos[i].productName);
			}
			this.obj.productCode = codeArr.join(',');
			this.obj.productName = nameArr.join(',');
		} else {
			var saveObj = [];
			var cacheObj = [];
			$.each(arrSampleInfos, function (idx, row) {
				cacheObj.push({ productCode: row.productCode, projectCode: row.projectCode });
			});
			if (productQuerySelectedRows) {
				$.each(productQuerySelectedRows, function (idx, row) {
					var r = { productCode: row.productCode, proejctCode: '' };
					var addrow = true;
					$.each(cacheObj, function (index, bean) {
						if (r.productCode == bean.productCode) {
							addrow = false;
							return false;
						}
					});
					if (addrow)
						cacheObj.push(r);
				});
			}
			if ($("#searchProduct").length > 0) {
				var selectRows = $("#searchProduct").combogrid('grid').datagrid('getSelections');
				for (var row in selectRows) {
					var bool = false;
					for (var j in cacheObj) {
						if (cacheObj[j].productCode == selectRows[row].productCode) {
							bool = true;
							break;
						}
					}
					if (!bool) {
						cacheObj.push(selectRows[row]);
					}
				}
			}
			//cacheObj--新数据  thatSampleInfos--就数据
			if (cacheObj.length == thatSampleInfos.length) {
				//直接修改
				$.each(cacheObj, function (i, row) {
					thatSampleInfos[i].productCode = row.productCode;
					thatSampleInfos[i].productName = row.productName;
					saveObj.push(thatSampleInfos[i]);
				});
			} else {
				//productCode相同修改，newProductCode在oldProductCodes中没找到添加，oldProductCode在newProductCodes中没找到，删除
				for (var i = 0; i < cacheObj.length; i++) {
					var find = false;
					var newData = cacheObj[i];
					for (var j = 0; j < thatSampleInfos.length; j++) {
						var oldData = thatSampleInfos[j];
						if (newData.productCode == oldData.productCode) {
							oldData.productCode = newData.productCode;
							oldData.productName = newData.productName;
							saveObj.push(oldData);
							find = true;
							break;
						}
					}
					if (!find) {
						//新产品在旧产品中没找到，需要添加
						saveObj.push(newData);
					}
				}
				var deleteInfoIds = [];
				for (var j = 0; j < thatSampleInfos.length; j++) {
					var find = false;
					var oldData = thatSampleInfos[j];
					for (var i = 0; i < cacheObj.length; i++) {
						var newData = cacheObj[i];
						if (newData.productCode == oldData.productCode) {
							find = true;
							break;
						}
					}
					if (!find) {
						//旧产品在新产品中没找到，需要删除
						deleteInfoIds.push(oldData.sampleInfoId);
					}
				}
				obj.deleteSampleInfoIdStr = deleteInfoIds.join(',');
			}
			/*			$.each(cacheObj,function(index,row) {
							var r = row;
							$.each(thatSampleInfos, function(index, bean) {
								var rPP = (r.productCode == null ? '' : r.productCode);// + (r.projectCode == null ? '' : r.projectCode);
								var bPP = (bean.productCode == null ? '' : bean.productCode);// + (bean.projectCode == null ? '' : bean.projectCode);
								if (rPP == bPP) {
									r = bean;
									return false;
								}
							});
							saveObj.push(r);
						});*/
			obj.sampleInfos = saveObj;
		}
	};
	this.setDat = function (id) {
		if (typeof (this.obj[id]) != 'undefined') {
			setDat(id, this.obj[id]);
		}
	};
	this.setDatYMD = function (id) {
		if (typeof (this.obj[id]) != 'undefined') {
			setDatYMD(id, this.obj[id]);
		}
	};
	this.setCk = function (id) {
		if (typeof (this.obj[id]) != 'undefined') {
			setCk(id, this.obj[id]);
		}
	};
	this.setCkArrMulti = function (id) {
		if (typeof (this.obj[id]) != 'undefined') {
			setCkArrMulti(id, this.obj[id]);
		}
	}
	this.setCkArr = function (id) {
		if (typeof (this.obj[id]) != 'undefined') {
			setCkArr(id, this.obj[id]);
		}
	}
	this.setCkVl = function (id) {
		if (typeof (this.obj[id]) != 'undefined') {
			setCkVl(id, this.obj[id]);
		}
	};
	this.setCkGrp = function (id, count) {
		if (typeof (this.obj[id]) != 'undefined') {
			setCkGrp(id, this.obj[id], count);
		}
	};
	this.setSel = function (id) {
		if (typeof (this.obj[id]) != 'undefined') {
			setSel(id, this.obj[id]);
		}
	};
	this.setVl = function (id) {
		if (typeof (this.obj[id]) != 'undefined') {
			setVl(id, this.obj[id]);
		}
	};
	this.setSampleInfos = function () {
		if (typeof (this.obj.sampleInfos) != 'undefined' && this.obj.sampleInfos != null) {
			setSampleInfos(this.obj.sampleInfos);
		} else {
			if (typeof (this.obj.productCode) != 'undefined' && typeof (this.obj.projectCode) != 'undefined') {
				setSamleInfosUpdate(this.obj.productCode, this.obj.productName, this.obj.projectCode);
			}
		}
	};

	this.getComboBox = function (id) {
		this.obj[id] = getComboBox(id);
	};
	this.setComboBox = function (id) {
		if (typeof (this.obj[id]) != 'undefined') {
			setComboBox(id, this.obj[id]);
		}
	};
	this.setComboGrid = function (id) {
		if (typeof (this.obj[id]) != 'undefined') {
			setComboGrid(id, this.obj[id]);
		}
	};
	this.setMutiComboGrid = function (id) {
		if (typeof (this.obj[id]) != 'undefined' && this.obj[id]) {
			setMutiComboGrid(id, this.obj[id].split(','));
		}
	}
}

function object(o) {
	function F() { };
	F.prototype = o;
	return new F();
}


function getUrlParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	var url = decodeURI(window.location.search);
	var r = url.substr(1).match(reg); //匹配目标参数
	if (r != null) return unescape(r[2]); return null; //返回参数值
}

function checkSampleNum() {
}

var tempAbs = {
	bean: null,
	sampleInfos: null,
	address: null,
	read: function (obj) { },
	readAbs: function (obj, isNew) {
		if (!obj) {
			obj = { customerCode: null, addressProvince: null, addressCity: null, addressCounty: null, addressTown: null };
		}
		if (obj.isCheck == 1) {
			//$(".container").attr("disabled",true);
			$("input,select").attr('disabled', true);
			$("a").attr("style", "display:none");
		}
		var customerCode = getUrlParam("customerCode");
		var customerName = getUrlParam("customerName");
		var productCode = getUrlParam("productCode");
		var productName = getUrlParam("productName");
		var bloodDate = getUrlParam("bloodDate");
		var sampleNum = getUrlParam("sampleNum");
		var sampleType = getUrlParam("sampleType");
		//alert("customerCode="+customerCode);
		if (customerCode && customerCode != '') {
			obj.customerCode = customerCode;
			obj.customerName = customerName;
		}
		if (productCode && productCode != '') {
			obj.productCode = productCode;
			obj.productName = productName;
		}
		if (bloodDate) {
			$("#bloodDate").val(bloodDate);
		}

		if (sampleType) {
			setCkArr("sampleType_1", sampleType);
		}
		this.bean = new Inital(obj);
		//		customerInitial(function(data) {
		//			if (obj.customerCode) {
		//				var noneRow = true;
		//				$.each(data.rows,function(idx,row) {
		//					if (row.customerCode == obj.customerCode) {
		//						noneRow = false;
		//						return false;
		//					}
		//				})
		//				if (noneRow) {
		//			    	data.rows.unshift({
		//			    		customerCode:obj.customerCode,
		//						customerName:obj.customerName
		//					});
		//				}
		//			}
		//	    	return data;
		//		});
		var otherProductCodes = [];
		if (obj.productCode && obj.productName) {
			var productCodes = obj.productCode.split(',');
			for (var i in productCodes) {
				if (productCodes[i]) {
					var productCheckBox = $("#product_" + productCodes[i]);
					if (productCheckBox.length < 1) {
						otherProductCodes.push(productCodes[i]);
					}
				}
			}
		}
		// productInitial(function(data) {
		// 	if (obj.productCode) {
		// 		var noneRow = true;
		// 		$.each(data.rows,function(idx,row) {
		// 			if (row.productCode == obj.productCode) {
		// 				noneRow = false;
		// 				return false;
		// 			}
		// 		})
		// 		if (noneRow) {
		// 	    	data.rows.unshift({
		// 	    		productCode:obj.productCode,
		// 	    		productName:obj.productName,
		// 	    		productInfo:obj.productCode+' '+obj.productName
		// 			});
		// 		}
		// 	}
		// 	return data;
		// });
		if (!isNew) {
			this.read(obj, this.bean);
		} else {
			$('#customerCode').combobox('setValue', obj.customerCode);
			this.bean.setSampleInfos();
		}

		if (obj.address) {
			// try {
			// 	var splitValue = obj.address.split("、");
			// 	if (splitValue.length == 5) {
			// 		$.ajax({
			// 			method: 'POST',
			// 			url: '/csfy/intf.do',
			// 			data: { method: 'getAddrs' },
			// 			success: function (res1) {
			// 				for (var index1 in res1.rows) {
			// 					var item1 = res1.rows[index1];
			// 					if (item1.name == splitValue[0]) {
			// 						setComboBox('area1', item1.code);
			// 						$.ajax({
			// 							method: 'POST',
			// 							url: '/csfy/intf.do',
			// 							data: { method: 'getAddrs', parentId: item1.code },
			// 							success: function (res2) {
			// 								for (var index2 in res2.rows) {
			// 									var item2 = res2.rows[index2];
			// 									if (item2.name == splitValue[1]) {
			// 										setComboBox('area2', item2.code);
			// 										$.ajax({
			// 											method: 'POST',
			// 											url: '/csfy/intf.do',
			// 											data: { method: 'getAddrs', parentId: item2.code },
			// 											success: function (res3) {
			// 												for (var index3 in res3.rows) {
			// 													var item3 = res3.rows[index3];
			// 													if (item3.name == splitValue[2]) {
			// 														setComboBox('area3', item3.code);
			// 														$.ajax({
			// 															method: 'POST',
			// 															url: '/csfy/intf.do',
			// 															data: { method: 'getAddrs', parentId: item3.code },
			// 															success: function (res4) {
			// 																for (var index4 in res4.rows) {
			// 																	var item4 = res4.rows[index4];
			// 																	if (item4.name == splitValue[3]) {
			// 																		setComboBox('area4', item4.code);
			// 																		break;
			// 																	}
			// 																}
			// 																$('#area4').combobox('loadData', res4.rows);
			// 															}
			// 														});
			// 														break;
			// 													}
			// 												}
			// 												$('#area3').combobox('loadData', res3.rows);
			// 											}
			// 										});
			// 										break;
			// 									}
			// 								}
			// 								$('#area2').combobox('loadData', res2.rows);
			// 							}
			// 						});
			// 						break;
			// 					}
			// 				}
			// 				$('#area1').combobox('loadData', res1.rows);
			// 			}
			// 		});
			// 		$("#addressStreet").val(splitValue[4]);
			// 	}
			// } catch (err) {
			// 	console.log(err);
			// }
		}
		if (customerCode && customerCode != '') {
			var customerCombogrid = $('#customerCode');
			if (customerCombogrid) {
				$('#customerCode').combobox('setValue', customerCode);
			}
		}


		if (otherProductCodes.length > 0) {
			//回显其他产品
			if ($("#searchProduct").length > 0) {
				$("#searchProduct").combogrid('setValues', otherProductCodes);
			}
		}
		//根据step，禁用样品编号、客户、产品
		if (/[01]{5}1[01]{2}/.test(obj.step)) {
			$("#customerCode").combogrid('disable');
			$("#tubeType").attr('disabled', true);
			$("input:checkbox[id^='product_']").each(function () {
				$(this).attr('disabled', true);
			});
			$(".sample-type").each(function () {
				$(this).children("input").eq(0).attr('disabled', true);
			});
			$("#searchProduct").combogrid('disable');
		}

	},
	save: function (bean) { },
	saveAbs: function () {
		this.save(this.bean);
		if (this.address) {
			// this.bean.obj.address = getComboBoxText('area1') + '、' + getComboBoxText('area2') + '、' + getComboBoxText('area3') + '、' + getComboBoxText('area4') + '、' + vl('addressStreet');
		}
		// var customerCodeCombo = $('#customerCode')
		// if (customerCodeCombo) {
		// 	var customerName = customerCodeCombo.combobox('getText');
		// 	var customerCode = customerCodeCombo.combobox('getValue');
		// 	this.bean.obj.customerName = customerName;
		// 	this.bean.obj.customerCode = customerCode;
		// }
		return this.bean.obj;
	},
	validateAbs: function (m) { },
	validate: function (notValidateArr) {
		notValidateArr = notValidateArr ? notValidateArr : '';
		var m = '';
		// if (isEmpty(vl('sampleNum')) && notValidateArr.indexOf('sampleNum') < 0) {
		// 	m += '<li>样品编号不能为空!</li>';
		// }
		//		else {
		//			if(typeof(checkSampleNum(1)) != "undefined"){
		//				m += '<li>样品编号重复!</li>';
		//			}
		//		}
		// if (isEmpty(getComboBox('customerCode'))) {
		// 	m += '<li>送检单位不能为空!</li>';
		// }

		/*var infos = getSampleInfos(temp.sampleInfos);
		//处理产品下来框
		if (infos.length == 0 && window.location.href.indexOf("akxChildGenTest.jsp") == -1) {
			m += '<li>产品不能为空!</li>';
		}*/

		// var sampleTypeArr = [];
		// var countSampleType = {};
		// $("input:checkbox[name^='sampleType_']").each(function () {
		// 	countSampleType[$(this).attr('name')] = 1;
		// });
		// for (var key in countSampleType) {
		// 	var val = ckArr(key);
		// 	if (val) {
		// 		sampleTypeArr.push(val);
		// 	}
		// }
		// var location = window.location.pathname;
		// if (sampleTypeArr.length < 1 && isEmpty(vl('sampleTypeOther'))) {
		// 	if (location.indexOf('HPV.jsp') < 0) {
		// 		m += '<li>样本类型不能为空!</li>';
		// 	}
		// }
		var emptyInput = [];//记录必填而没有填写的控件
		//字段验证（可扩展validate属性）add by liuyuzhuo
		$("[validate]").each(function () {
			var validate = $(this).attr('validate');
			if (validate) {
				var value = '';//
				if ($(this).is('input')) {
					value = $(this).val();
				} else if ($(this).is('select')) {
					value = sel($(this).attr('id'));
				} else if ($(this).is('span') && $(this).hasClass('group-field')) {
					var childs = $(this).children('input');
					var checkArr = [];
					for (var i = 0; i < childs.length; i++) {
						if ($(childs[i]).is(':checked')) {
							checkArr.push($(childs[i]).attr('id').split('_')[1]);
						}
					}
					value = checkArr.join(',');
				} else {
					return true;
				}
				var validateArr = validate.split(',');
				for (var i = 0; i < validateArr.length; i++) {
					switch (validateArr[i]) {
						case 'idCard':
							var reg1 = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
							var reg2 = /^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$/;
							if (value.length > 14) {
								if (value && (!reg1.test(value) && !reg2.test(value))) {
									m += '<li>' + $(this).parent().text().split('：')[0] + '格式非法!</li>';
									emptyInput.push($(this));
								}
							}
							break;
						case 'phoneNum':
							if (value && !checkTel(value)) {
								m += '<li>' + $(this).parent().text().split('：')[0] + '格式非法!</li>';
								emptyInput.push($(this));
							} else if (value && value.charAt(0) == '1' && value.length != 11) {
								m += '<li>' + $(this).parent().text().split('：')[0] + '格式非法!</li>';
								emptyInput.push($(this));
							}
							break;
						case 'required':
							if ($(this).hasClass('easyui-datebox')) {
								var inputId = $(this).attr('id');
								var v = dat(inputId);
								if (!v) {
									m += '<li>' + $(this).parent().text().split('：')[0] + '不能为空!</li>';
									emptyInput.push($(this));
								}
							} else {
								if (!value) {
									var info = '';
									if ($(this).is("span")) {
										info = $(this).text().split('：')[0];
										var inputs = $(this).find("input");
										inputs.off("change");
										inputs.on("change", function () {
											$(this).parent().css('background-color', "#FFF");
										})
									} else {
										info = $(this).parent().text().split('：')[0];
									}
									m += '<li>' + info.split('？')[0] + '不能为空!</li>';
									emptyInput.push($(this));
								}
							}
							break;
						case 'email':
							var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
							if (value && !reg.test(value)) {
								m += '<li>' + $(this).parent().text().split('：')[0] + '格式非法!</li>';
								emptyInput.push($(this));
							}
							break;
						case 'int':
							var reg = /^\d+$/;
							if (value && !reg.test(value)) {
								m += '<li>' + $(this).parent().text().split('：')[0] + '格式非法!</li>';
								emptyInput.push($(this));
							}
							break;
						default:
							break;
					}
					if (validateArr[i].indexOf('maxlength') >= 0) {
						var len = validateArr[i].substring(validateArr[i].indexOf('[') + 1, validateArr[i].indexOf(']'));
						if (value && value.length > parseInt(len)) {
							m += '<li>' + $(this).parent().text().split('：')[0] + '长度超过限制!</li>';
							emptyInput.push($(this));
						}
					} else if (validateArr[i].indexOf('length[') >= 0) {
						var len = validateArr[i].substring(validateArr[i].indexOf('[') + 1, validateArr[i].indexOf(']'));
						if (value && value.length != parseInt(len)) {
							m += '<li>' + $(this).parent().text().split('：')[0] + '长度非法!</li>';
							emptyInput.push($(this));
						}
					}
				}
			}
		});

		//限制日期根式
		$("input[type='date']").each(function () {
			if ($(this).hasClass('easyui-datebox')) {
				var inputId = $(this).attr('id');
				var v = dat(inputId);
				if (v) {
					var reg = /^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$/;
					if (!reg.test(v)) {
						m += '<li>' + $(this).parent().text().split('：')[0] + '非法!</li>';
					}
				}
			} else {
				var value = $(this).val();
				if (value && !$(this).hasClass('textbox-text')) {
					var reg = /^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$/;
					if (!reg.test(value)) {
						m += '<li>' + $(this).parent().text().split('：')[0] + '非法!</li>';
						emptyInput.push($(this));
					}
				}
			}
		});
		//输入有问题的控件背景标红
		for (var i = 0; i < emptyInput.length; i++) {
			// emptyInput[i].css('background-color', "#F00");
			if (emptyInput[i].hasClass('easyui-datebox') && !isChrome) {
				emptyInput[i].datebox({
					onSelect: function (date) {
						if ($(this).datebox('getValue')) {
							$(this).parent().find(".datebox").find(".validatebox-text").css('background-color', "#FFF");
						}
					}
				});
				// emptyInput[i].parent().find(".datebox").find(".validatebox-text").css('background-color', "#F00");
			} else {
				emptyInput[i].off('valuechange');
				emptyInput[i].on('valuechange', function (e, previous) {
					if ($(this).val()) {
						$(this).css('background-color', "#FFF");
					}
					if ($(this).attr("id") == 'idCard' && typeof (autoBirthDayAndAge) == 'function') {
						autoBirthDayAndAge();
					}
				})
			}
		}
		return this.validateAbs(m);
	}
}
//电话号码验证（座机和手机）
function checkTel(value) {
	var isPhone = /^([0-9]{3,4}-?)?[0-9]{7,8}$/;
	var isMob = /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;
	if (isMob.test(value) || isPhone.test(value)) {
		return true;
	} else {
		return false;
	}
}
function dat(id) {
	return $('#' + id).datebox('getValue');
}

function setDat(id, value) {
	$('#' + id).datebox('setValue', value);
}

function datYMD(id) {
	var Year = vl(id + '_Year');
	var Month = vl(id + '_Month');
	var Day = vl(id + '_Day');
	return mergeDate(Year, Month, Day);
}

function setDatYMD(id, value) {
	if (value) {
		var times = [];
		times = value.split('-');
		setVl(id + '_Year', times[0]);
		setVl(id + '_Month', times[1]);
		var s = times[2];
		var arr = s.split(' ');
		if (arr != null && arr.length > 1) {
			s = arr[0];
		}
		setVl(id + '_Day', s);
	} else {
		setVl(id + '_Year', '');
		setVl(id + '_Month', '');
		setVl(id + '_Day', '');
	}
}

function mergeDate(Y, M, D) {
	if (isEmpty(Y) && isEmpty(M) && isEmpty(D)) {
		return null;
	}
	var strDat = Y + '-' + M + '-' + D;
	var r = strDat.match(/^(?:(?!0000)[0-9]{4}([-]?)(?:(?:0?[1-9]|1[0-2])\1(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])\1(?:29|30)|(?:0?[13578]|1[02])\1(?:31))|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-]?)0?2\2(?:29))$/);
	if (r == null) {
		return '';
	}
	return strDat;
}

function ckVl(id) {
	var ck = $('#' + id);
	if (ck.is(':checked')) {
		return ck.val();
	} else {
		return null;
	}
}

function setCkVl(id, value) {
	var ck = $('#' + id);
	if (typeof (value) != 'undefined' && value != null && value != '0') {
		ck.attr('checked', true);
	} else {
		ck.removeAttr('checked');
	}
}

function ck(id) {
	if ($('#' + id).is(':checked')) {
		return '1';
	} else {
		return '0';
	}
}

function setCk(id, value) {
	var ck = $('#' + id);
	if (typeof (value) != 'undefined' && value != null && value != '0') {
		ck.attr('checked', true);
	} else {
		ck.removeAttr('checked');
	}
}

function setCkArr(id, value) {
	$('input[name="' + id + '"]').each(function (idx, ck) {
		if (!value) return false;
		if (value == $(ck).val()) {
			$(ck).attr('checked', true);
		} else {
			$(ck).removeAttr('checked');
		}
	});
}

function ckArrMulti(name) {
	var result = '';
	$('input:checkbox[name="' + name + '"]').each(function (idx, ck) {
		if ($(ck).is(':checked')) {
			result += $(ck).val() + ';';
		}
	})
	return result;
}

function setCkArrMulti(name, value) {
	if (typeof (value) == 'undefined' || !!value == false) {
		return;
	}
	var arr = value.split(';')
	$('input:checkbox[name="' + name + '"]').each(function (idx, ck) {
		var hasChecked = false;
		$.each(arr, function (index, arrValue) {
			if ($(ck).val() == arrValue) {
				$(ck).attr('checked', true);
				hasChecked = true;
				return false
			}
		})
		if (!hasChecked) {
			$(ck).removeAttr('checked');
		}
	});
}

function ckArr(id) {
	var result = '';
	$('input[name="' + id + '"]').each(function (idx, ck) {
		if ($(ck).is(':checked')) {
			result = $(ck).val();
			return false;
		}
	});
	return result;
}

function ckGrp(id, count) {
	var result = '';
	if (typeof (count) != 'undefined' && count instanceof Array) {
		for (var i = 0; i < count.length; i++) {
			var ckGrp = $('#' + id + '_' + count[i]);
			if (ckGrp.is(':checked')) {
				result = count[i] + '';
				break;
			}
		}
	} else {
		var cnt = 2;
		if (typeof (count) != 'undefined') {
			if ($.isNumeric(count)) {
				cnt = count;
			}
		}
		for (var i = 0; i < cnt; i++) {
			var ckGrp = $('#' + id + '_' + i);
			if (ckGrp.is(':checked')) {
				result = i + '';
				break;
			}
		}
	}
	return result;
}

function setCkGrp(id, value, count) {
	if (typeof (count) != 'undefined' && count instanceof Array) {
		for (var i = 0; i < count.length; i++) {
			var ckGrp = $('#' + id + '_' + count[i]);
			if (count[i] == value) {
				ckGrp.attr('checked', true);
			} else {
				ckGrp.removeAttr('checked');
			}
		}
	} else {
		var cnt = 2;
		if (typeof (count) != 'undefined') {
			if ($.isNumeric(count)) {
				cnt = count;
			}
		}
		for (var i = 0; i < cnt; i++) {
			var ckGrp = $('#' + id + '_' + i);
			if (i == value) {
				ckGrp.attr('checked', true);
			} else {
				ckGrp.removeAttr('checked');
			}
		}
	}
}

function sel(id) {
	return $('#' + id + ' option:selected').val();
}

function setSel(id, value) {
	$('#' + id + ' option[value="' + value + '"]').attr('selected', true);
	$('#' + id).change();
}

function setVl(id, value) {
	$('#' + id).val(value);
	if (id == 'sampleNum') {
		if ($(window.parent.document).find("input[id='isEdit']").val() == '1' && !value) {
			$('#' + id).attr('readonly', true);
		}
	}
}

function setComboGrid(id, value) {
	$('#' + id).combogrid('setValue', value);
}
function setMutiComboGrid(id, values) {
	$('#' + id).combogrid('setValues', values);
}

function setComboBox(id, value) {
	$('#' + id).combobox('setValue', value);
}

function getComboBox(id) {
	return $('#' + id).combobox('getValue');
}
function getComboBoxText(id) {
	return $('#' + id).combobox('getText');
}

function getComboGrid(id) {
	return $('#' + id).combobox('getValue');
}

function vl(id) {
	if ($('#' + id)) {
		return $.trim($('#' + id).val());
	} else {
		return '';
	}
}

function ckb(id) {
	return $('#' + id).is(':checked');
}

function isNotEmpty(data) {
	return (typeof (data) == 'undefined' || data == null || data == "") ? false : true;
}

function isEmpty(data) {
	return (typeof (data) == 'undefined' || data == null || data == "") ? true : false;
}

function setSamleInfosUpdate(products, productNs, projects) {
	if (products) {
		var productCodes = products.split(',');
		var productNames = productNs.split(',');
		var noChkProduct = [];
		$.each(productCodes, function (idx, s) {
			if ($('#product_' + s)[0]) {
				setCk('product_' + s, 1);
			} else {
				noChkProduct.push({ productCode: s, productName: productNames[idx] });
			}
		});

		if ($('#productQuery')[0])
			queryProductInitalLocal(noChkProduct);
	}
	if (projects) {
		var projectCodes = projects.split(',');
		$.each(projectCodes, function (idx, s) {
			setCk('project_' + s, 1);
		});
	}
}

function queryProductInitalLocal(rows, id) {
	var values = [];
	/*	queryProductInital(function(data) {
			if (rows.length>0) {
				$.each(rows,function(idx, obj) {
					data.rows.push({
						productCode:obj.productCode,
						productName:obj.productName
					});
				})
			}
			return data;
		});*/
	$.each(rows, function (idx, obj) {
		values.push(obj.productCode);
	});
	$('#' + id).combogrid('setValues', values);
	/*	if(id=='searchProduct'){
			$("#productCodes").val(values.join(','));
		}*/
}

function setSampleInfos(codes) {
	if (codes) {
		var noChkProduct = [];
		$.each(codes, function (idx, s) {
			if (s.productCode) {
				if ($('#product_' + s.productCode)[0]) {
					setCk('product_' + s.productCode, 1);
				} else {
					noChkProduct.push({ productCode: s.productCode, productName: s.productName });
				}
			}
			if (s.projectCode) {
				setCk('project_' + s.projectCode, 1);
			}
		});
		if ($('#productQuery')[0]) {
			queryProductInitalLocal(noChkProduct, 'productQuery');
		}
		if ($('#searchProduct')[0]) {
			queryProductInitalLocal(noChkProduct, 'searchProduct');
		}

	}
}

function checkSampleInfos(codes) {
	var hasProduct = false;
	if (codes) {
		$.each(codes, function (idx, s) {
			if (ckb('product_' + s.productCode)) {
				hasProduct = true;
				return false;
			}
		});
	}
	return hasProduct;
}

function getSampleInfosUpdate(codes, obj) {
	obj.productCode = '';
	obj.productName = '';
	obj.projectCode = '';
	obj.projectName = '';
	if (codes) {
		var projectCount = 0;
		$.each(codes, function (idx, s) {
			if (ckb('product_' + s.productCode) || ckb('project_' + s.projectCode)) {
				if (obj.productCode) {
					obj.productCode += ',';
					obj.productName += ',';
					obj.projectCode += ',';
					obj.projectName += ',';
				}
				if (ckb('project_' + s.projectCode)) {
					projectCount++;
				}
				var pd_name = '';
				var pdn = $('#productName_' + s.productCode);
				var pdni = pdn.find('.t-product-name');
				if (pdni && pdni.length > 0) {
					pd_name = pdni.html();
				} else {
					pd_name = pdn.html();
				}

				var pj_name = $('#projectName_' + s.projectCode).text();
				if (typeof (pd_name) == 'undefined') pd_name = '';
				if (typeof (pj_name) == 'undefined') pj_name = '';
				obj.productCode += s.productCode;
				obj.productName += pd_name;
				obj.projectCode += s.projectCode;
				obj.projectName += pj_name;
			}
		});
		if (projectCount == 0) {
			obj.projectCode = '';
			obj.projectName = '';
		}
	}
	return obj;
}

function getSampleInfos(codes) {
	var sampleInfos = [];
	if (codes) {
		$.each(codes, function (idx, s) {
			if (ckb('product_' + s.productCode) || ckb('project_' + s.projectCode)) {
				var pd_name = '';
				var pdn = $('#productName_' + s.productCode);
				var pdni = pdn.find('.t-product-name');
				if (pdni && pdni.length > 0) {
					pd_name = pdni.html();
				} else {
					pd_name = pdn.html();
				}
				var pj_name = $('#projectName_' + s.projectCode).text();
				if (typeof (pd_name) == 'undefined') pd_name = '';
				if (typeof (pj_name) == 'undefined') pj_name = '';
				sampleInfos.push({
					'productCode': s.productCode,
					'productName': pd_name,
					'projectCode': s.projectCode,
					'projectName': pj_name
				});
			}
		});
	}
	if ($("#searchProduct").length > 0) {
		var text = $("#searchProduct").combogrid('getText');
		if (text) {
			var selectArr = text.split(',');
			for (var i in selectArr) {
				var datas = selectArr[i].split(' ');
				var bool = false;
				for (var si in sampleInfos) {
					if (sampleInfos[si].productCode == datas[0]) {
						bool = true;
						break;
					}
				}
				if (!bool) {
					sampleInfos.push({ "productCode": datas[0], "productName": datas[1] });
				}
			}
		}
	}
	return sampleInfos;
}
function ischeckItem() {
	for (var i = 0; i < checkedItems.length; i++) {
		$('#maingrid').datagrid('selectRecord', checkedItems[i]); //根据id选中行 
	}
}

function findCheckedItem(ID) {
	for (var i = 0; i < checkedItems.length; i++) {
		if (checkedItems[i] == ID) return i;
	}
	return -1;
}

function addcheckItem() {
	var row = $('#maingrid').datagrid('getChecked');
	for (var i = 0; i < row.length; i++) {
		if (findCheckedItem(row[i].id) == -1) {
			checkedItems.push(row[i].id);
		}
	}
}
function removeAllItem(rows) {

	for (var i = 0; i < rows.length; i++) {
		var k = findCheckedItem(rows[i].id);
		if (k != -1) {
			checkedItems.splice(i, 1);
		}
	}
}
function removeSingleItem(rowIndex, rowData) {
	var k = findCheckedItem(rowData.id);
	if (k != -1) {
		checkedItems.splice(k, 1);
	}
}
String.prototype.endWith = function (s) {
	if (s == null || s == "" || this.length == 0 || s.length > this.length)
		return false;
	if (this.substring(this.length - s.length) == s)
		return true;
	else
		return false;
	return true;
}
